from rest_framework.permissions import BasePermission
from rest_framework.exceptions import ParseError, PermissionDenied

from apps.system.models import Permission
from conf.config import METHOD_LIST
import re


class CustomPermission(BasePermission):
    """
    自定义角色的权限校验类
    这里没有配置白名单，可以在views层中指定权限
    permission_classes = (IsAuthenticated,)
    """

    def has_permission(self, request, view):
        # 采用url地址和提交类型判断
        method = request.method.upper()  # 当前请求方法

        if method not in METHOD_LIST:
            raise ParseError({'code': 400, 'msg': '不允许的提交方式！'})
        if request.user.is_superuser:
            return True

        urls = request.path  # 当前请求接口

        urls_list = urls.split('/')

        urls_list = list(filter(None, urls_list))  # 过滤掉空值
        urls_list = urls_list[1:]  # 去掉前缀api和版本等
        urls_pattern = r'^\d+$'  # 匹配一个或多个数字
        urls_repl = '{id}'  # 替换为'{id}'
        new_urls = ''
        for item in urls_list:
            new_urls += '/' + re.sub(urls_pattern, urls_repl, item)

        new_urls += '/'

        user = request.user
        print(request.user)
        role_list = user.role_set.filter(is_active=True).all()
        permissions = []
        for role in role_list:
            if len(role.permissions) > 0:
                permissions = list(set(permissions + role.permissions.split(',')))

        if len(permissions) > 0:
            permission = Permission.objects.filter(id__in=permissions, is_active=True, urls=new_urls,
                                                   method_types=method).first()
            if permission:
                return True

        raise PermissionDenied({'code': 403, 'msg': '没有权限'})
